import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../bean/player.dart';
import '../bean/skill/skill.dart';

class GameGlobal {
  static Player player = Player("我");

  static Skill? selectSkill;

  static late SharedPreferences _preferences;

  static Map<String, String> monsterNormalMap = {};
  static Map<String, String> monsterBossMap = {};

  static Map<String, String> equipmentMap = {
    'equip001': '木剑',
    'equip002': '草帽',
    'equip003': '布衣',
    'equip004': '草鞋',
    //横扫套
    'equip005': '横扫头',
    'equip006': '横扫甲',
    'equip007': '横扫鞋',
    'equip008': '横扫剑',
    //猛击套
    'equip009': '猛击头',
    'equip010': '猛击甲',
    'equip011': '猛击鞋',
    'equip012': '猛击锤',
    //神器
    'equip013': 'GM之手',
  };

  static Map<String, String> effectMap = {'effect001': '割裂', 'effect002': '削血'};
  static Map<String, String> suitMap = {'suit001': '割裂套', 'suit002': '削血套'};

  static Future init() async {
    WidgetsFlutterBinding.ensureInitialized();
    //怪物信息列表
    _initMonsterMap();
    //玩家信息缓存
    _preferences = await SharedPreferences.getInstance();
    var playerJson = _preferences.getString("playerJson");
    debugPrint("恢复玩家信息:$playerJson");
    if (playerJson != null) {
      try {
        player = jsonDecode(playerJson);
      } catch (e) {
        debugPrint(e.toString());
      }
    }
  }

  ///通过json文件初始化怪物名称
  static Future _initMonsterMap() async {
    var monsterJson = await rootBundle.loadString('assets/monster.json');
    debugPrint(monsterJson);
    Map<String, dynamic> monsterMap;
    monsterMap = jsonDecode(monsterJson);
    Map<String, dynamic> normal = monsterMap['normal'];
    Map<String, dynamic> boss = monsterMap['boss'];
    monsterNormalMap =
        normal.map((key, value) => MapEntry(key, value.toString()));
    monsterBossMap = boss.map((key, value) => MapEntry(key, value.toString()));
    debugPrint(monsterNormalMap.toString());
    debugPrint(monsterBossMap.toString());
  }

  // 保存角色信息 TODO Player对象太复杂，无法直接解析
  static savePlayer() {
    var map = Map();
    map["equip"] = "1";
    var playerJson = jsonEncode(map);
    debugPrint("保存玩家信息:$playerJson");
    _preferences.setString("playerJson", playerJson);
  }
}

extension EnemyNameExtend on String {
  String enemyName() => _commonName(GameGlobal.monsterNormalMap);

  ///装备名称词典
  String equipName() => _commonName(GameGlobal.equipmentMap);

  String effectName() => _commonName(GameGlobal.effectMap);

  String suitName() => _commonName(GameGlobal.suitMap);

  String _commonName(Map<String, String> map) {
    var name = map[this];
    if (name == null) {
      return "未知";
    } else {
      return name;
    }
  }
}
